﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace ETA.Common
{
    /// <summary>
    /// 通用工具类
    /// </summary>
    public static class CommHelper
    {
        /// <summary>
        /// 获取配置文件节点
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetValue(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }

        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static string GetMD5(string str, int code, bool isNeedToken = true)
        {
            if (isNeedToken)
            {
                str += GetValue("MD5Str");
            }
            if (code == 16) //16位MD5加密（取32位加密的9~25字符） 
            {
                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower().Substring(8, 16);
            }
            if (code == 32) //32位加密 
            {
                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower();
            }
            return null;
        }

        /// <summary>
        /// 短信发送
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public static bool SendMsg(string mobile, string content)
        {
            var res = false;
            try
            {
                var url = Config.SMSUrl;
                var account = Config.SMSAccount;
                var password = Config.SMSPassword;
                var subCode = Config.SMSSubCode;
                content = Config.SMSPrefix + content;
                Encoding encoding = Encoding.GetEncoding("UTF-8");
                UTF8Encoding utf8 = new UTF8Encoding();
                content = utf8.GetString(utf8.GetBytes(content));
                IDictionary<string, string> parameters = new Dictionary<string, string>();
                parameters.Add("Account", account);
                parameters.Add("Password", GetMD5(password, 32,false));
                parameters.Add("SubCode", subCode);
                parameters.Add("Phone", mobile);
                parameters.Add("Content", content);
                HttpWebResponse response = CreatePostHttpResponse(url, parameters, null, null, encoding, null);
                XmlDocument doc = new XmlDocument();
                doc.Load(response.GetResponseStream());
                var responseArr = doc.GetElementsByTagName("response");
                if (responseArr != null && responseArr.Count > 0)
                {
                    res = responseArr[0].InnerText == "1";
                }
            }
            catch (Exception)
            {
                res = false;
            }
            return res;
        }


        /// <summary>  
        /// 创建POST方式的HTTP请求  
        /// </summary>  
        /// <param name="url">请求的URL</param>  
        /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>  
        /// <param name="timeout">请求的超时时间</param>  
        /// <param name="userAgent">请求的客户端浏览器信息，可以为空</param>  
        /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>  
        /// <param name="cookies">随同HTTP请求发送的Cookie信息，如果不需要身份验证可以为空</param>  
        /// <returns></returns>  
        public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            if (requestEncoding == null)
            {
                throw new ArgumentNullException("requestEncoding");
            }
            HttpWebRequest request = null;
            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            if (!string.IsNullOrEmpty(userAgent))
            {
                request.UserAgent = userAgent;
            }
            else
            {
                request.UserAgent = "";
            }

            if (timeout.HasValue)
            {
                request.Timeout = timeout.Value;
            }
            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            //如果需要POST数据  
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
                byte[] data = requestEncoding.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            return request.GetResponse() as HttpWebResponse;
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="email">邮箱</param>
        /// <param name="content">正文内容</param>
        /// <returns></returns>
        public static bool SendEmail(string email,  string content,string subject=null)
        {
            var sfrom = Config.EmailFrom;
            var sfromer = Config.EmailFromer;
            var sto = email;
            var stoer = email;
            var sSubject = subject;
            var sBody = content;
            var sSMTPHost = Config.SMTPHost;
            var sSMTPuser = Config.SMTPuser;
            var sSMTPpass = Config.SMTPpass;
            return Sendmail(sfrom, sfromer, sto, stoer, sSubject, sBody, null, sSMTPHost, sSMTPuser, sSMTPpass);
        }

        /// <summary>
        /// C#发送邮件函数
        /// </summary>
        /// <param name="from">发送者邮箱</param>
        /// <param name="fromer">发送人</param>
        /// <param name="to">接受者邮箱</param>
        /// <param name="toer">收件人</param>
        /// <param name="Subject">主题</param>
        /// <param name="Body">内容</param>
        /// <param name="file">附件</param>
        /// <param name="SMTPHost">smtp服务器</param>
        /// <param name="SMTPuser">邮箱</param>
        /// <param name="SMTPpass">密码</param>

        /// <returns></returns>
        public static bool Sendmail(string sfrom, string sfromer, string sto, string stoer, string sSubject, string sBody, string sfile, string sSMTPHost, string sSMTPuser, string sSMTPpass)
        {
            ////设置from和to地址
            MailAddress from = new MailAddress(sfrom, sfromer);
            MailAddress to = new MailAddress(sto, sto);

            ////创建一个MailMessage对象
            MailMessage oMail = new MailMessage(from, to);

            //// 添加附件
            if (!string.IsNullOrEmpty(sfile))
            {
                oMail.Attachments.Add(new Attachment(sfile));
            }

            ////邮件标题
            oMail.Subject = sSubject;

            ////邮件内容
            oMail.Body = sBody;

            ////邮件格式
            oMail.IsBodyHtml = false;

            ////邮件采用的编码
            oMail.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312");

            ////设置邮件的优先级为高
            oMail.Priority = MailPriority.High;

            ////发送邮件
            SmtpClient client = new SmtpClient();
            ////client.UseDefaultCredentials = false;
            client.Host = sSMTPHost;
            client.Credentials = new NetworkCredential(sSMTPuser, sSMTPpass);
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Port = 25;
            try
            {
                client.Send(oMail);
                return true;
            }
            catch (Exception err)
            {
                Logger.Log.Error(err.Message);
                return false;
            }
            finally
            {
                ////释放资源
                oMail.Dispose();
            }

        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string Base64Encrypt(string source)
        {
            return System.Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(source));
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="encryptedStr"></param>
        /// <returns></returns>
        public static string Base64Dencrypt(string encryptedStr)
        {
            try
            {
                return System.Text.Encoding.Default.GetString(System.Convert.FromBase64String(encryptedStr));
            }
            catch (Exception e)
            {
                return "";
            }
        }
    }
}
